import React, { Component, useState } from 'react';
import { Button, Input, Select } from 'antd';
import { connect } from 'umi';

import styles from './style.less';
import { createFromIconfontCN } from '@ant-design/icons';
const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1796398_24zx598o8ub.js', // 在 iconfont.cn 上生成
});

const PriceInput = ({ value = {}, onChange }) => {
  const [number, setNumber] = useState(0);
  const [currency, setCurrency] = useState('rmb');

  const triggerChange = (changedValue) => {
    if (onChange) {
      onChange({
        number,
        currency,
        ...value,
        ...changedValue,
      });
    }
  };

  const onNumberChange = (e) => {
    const newNumber = parseInt(e.target.value || 0, 10);
    if (Number.isNaN(number)) {
      return;
    }

    if (!('number' in value)) {
      setNumber(newNumber);
    }

    triggerChange({
      number: newNumber,
    });
  };

  const onCurrencyChange = (newCurrency) => {
    if (!('currency' in value)) {
      setCurrency(newCurrency);
    }

    triggerChange({
      currency: newCurrency,
    });
  };

  return (
    <span>
      <Input
        type="text"
        value={value.number || number}
        onChange={onNumberChange}
        style={{
          width: 100,
        }}
      />
      <Select
        value={value.currency || currency}
        style={{
          width: 80,
          margin: '0 8px',
        }}
        onChange={onCurrencyChange}
      >
        <Select.Option value="rmb">RMB</Select.Option>
        <Select.Option value="dollar">Dollar</Select.Option>
      </Select>
    </span>
  );
};

// @connect(({ blank }) => blank)
class Page extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'blank/fetch',
    });
  }

  render() {
    const { text, a } = this.props.blank;
    return (
      <div className={styles.container}>
        <h1>a:{a}</h1>
        <MyIcon type="icon-hezuo" style={{ fontSize: '30px', color: '#08c' }} />
        <Button
          onClick={() => {
            this.props.dispatch({ type: 'blank/add', payload: 4 });
          }}
        >
          {text}
        </Button>
        <div>
          {' '}
          <PriceInput />
        </div>
      </div>
    );
  }
}

export default connect(({ blank }) => ({ blank }))(Page);
